﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DbSQLite;



namespace Callchecker
{
    public partial class FormHistoryMessage : Form
    {
        public FormHistoryMessage()
        {
            InitializeComponent();
        }

        #region События

        private void FormHistoryMessage_Load(object sender, EventArgs e)
        {
            GetMessages();

            dgHistory.Columns[0].Width = 100;
            dgHistory.Columns[2].Width = 500;

            dtpFrom.ValueChanged += dtp_ValueChanged;
            dtpTo.ValueChanged += dtp_ValueChanged;
            tsHistory.Items.Add(new ToolStripControlHost(dtpFrom));
            tsHistory.Items.Add(new ToolStripControlHost(new Label() { Text = " по ", TextAlign = ContentAlignment.MiddleCenter}));
            tsHistory.Items.Add(new ToolStripControlHost(dtpTo));
        }
        private void btnLog_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                Common.ShowLog();
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void tsmiHistory_Click(object sender, EventArgs e)
        {
            btnFind_Click(null, null);
        }
        private void btnFind_Click(object sender, EventArgs e)
        {
            GetMessages();
        }
        private void FormHistoryMessage_KeyDown(object sender, KeyEventArgs e)
        {
            //Получене справки
            if (e.KeyCode == Keys.F1)
            {
                try
                {
                    Common.GetHelp("mf_history", HelpNavigator.Topic);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
                return;
            }

            // Закрытие формы по Ctrl-F4
            if (e.Control && e.KeyCode == Keys.F4)
            {
                this.Close();
                return;
            }

            // Обновление данных на форме по комбинации клавиш
            if ((dtpFrom.Focused || dtpTo.Focused) && e.KeyCode == Keys.Enter)
            {
                btnFind_Click(null, null);
                return;
            }
            if (dgHistory.Focused && e.Control && e.KeyCode == Keys.R)
            {
                btnFind_Click(null, null);
                return;
            }

        }
        private void tsbSettings_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                Common.FormMain.Show();
                Common.FormMain.ShowInTaskbar = true;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// Отслеживает, чтобы значение в контроле dtpFrom было всегда меньше или равно значению в dtpTo
        /// </summary>
        private void dtp_ValueChanged(object sender, EventArgs e)
        {
            Control ctrl = sender as Control;
            if (ctrl != null)
            {
                switch (ctrl.Name)
                {
                    case "dtpFrom":
                        if (dtpFrom.Value.Date > dtpTo.Value.Date) dtpTo.Value = dtpFrom.Value;
                        break;
                    case "dtpTo":
                        if (dtpTo.Value.Date < dtpFrom.Value.Date) dtpFrom.Value = dtpTo.Value;
                        break;
                    default:
                        break;
                }
            }
        }
        private void dgHistory_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2)
                FormShowDetails.Item(
                    Convert.ToDateTime(dgHistory.Rows[e.RowIndex].Cells[1].Value),
                    dgHistory.Rows[e.RowIndex].Cells[2].Value.ToString(),
                    dgHistory.Rows[e.RowIndex].Cells[3].Value.ToString()
                    ).ShowDialog();
        }
        private void tsmiDetails_Click(object sender, EventArgs e)
        {
            if (dgHistory.SelectedCells.Count > 0)
            {
                dgHistory_CellDoubleClick(null, new DataGridViewCellEventArgs(dgHistory.SelectedCells[0].ColumnIndex, dgHistory.SelectedCells[0].RowIndex));
            }
        }
        private void cmsHistory_Opened(object sender, EventArgs e)
        {
            tsmiDetails.Enabled = (dgHistory.SelectedCells.Count > 0 && dgHistory.SelectedCells[0].ColumnIndex == 2);
        }
        private void FormHistoryMessage_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            try
            {
                Common.GetHelp("mf_history", HelpNavigator.Topic);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
        
        #endregion

        #region Вспомогательные функции

        /// <summary>
        /// Получение списка сообщений за период указанный в фильтре
        /// </summary>
        private void GetMessages()
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                ParametersCollection parameters = new ParametersCollection();

                dgHistory.DataSource = SQ_Message.SequenceByDate(dtpFrom.Value.Date, dtpTo.Value.AddDays(1).Date);
                dgHistory.Columns["id"].Visible = false;
                dgHistory.Columns["dt"].HeaderText = LogMessage.ColumnHeaderDT;
                dgHistory.Columns["msg"].HeaderText = LogMessage.ColumnHeaderMSG;
                dgHistory.Columns["details"].Visible = false;

                tsslCountOfRecords.Text = String.Format(LogMessage.StatusBarMessageHistory, dgHistory.RowCount);

            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        #endregion

        private DateTimePicker dtpFrom = new DateTimePicker() { Width = 124, Name = "dtpFrom" };
        private DateTimePicker dtpTo = new DateTimePicker() { Width = 124, Name = "dtpTo" };

    }
}
